package org.cheniy.domain.strategy.service.rule.chain.factory;


import lombok.*;
import org.cheniy.domain.strategy.model.entity.StrategyEntity;
import org.cheniy.domain.strategy.repository.IStrategyRepository;
import org.cheniy.domain.strategy.service.rule.chain.ILogicChain;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author cheniy
 * @description 责任链工厂-进行责任链的节点拼接
 * @create 2025/3/6 12:48
 */
@Service
public class DefaultChainFactory {

    public Map<String, ILogicChain> logicChainMap = new ConcurrentHashMap<>();

    protected IStrategyRepository iStrategyRepository;

    public DefaultChainFactory(Map<String, ILogicChain> logicChainMap, IStrategyRepository iStrategyRepository) {
        this.logicChainMap = logicChainMap;
        this.iStrategyRepository = iStrategyRepository;
    }

    public ILogicChain openLogicChain(Long strategyId) {

        // 1. 根据strategyId获取到当前策略的规则，分离出来成为数组
        StrategyEntity strategyEntity = iStrategyRepository.queryStrategyByStrategyId(strategyId);
        String[] ruledModels = strategyEntity.ruleModels();

        // 2. 若是没有规则则返回兜底作为头节点
        if (null==ruledModels||ruledModels.length==0) return logicChainMap.get("default");
        // 2. 遍历规则数组，根据顺序连接节点
        // 获取头节点
        ILogicChain headerLogicChain = logicChainMap.get(ruledModels[0]);
        // 连接节点
        for (int i = 1; i < ruledModels.length; i++) {
            ILogicChain logicChainNode=logicChainMap.get(ruledModels[i]);
            headerLogicChain= headerLogicChain.appendNext(logicChainNode);
        }
        // 3. 补充连接兜底节点-数据库中没有，需要额外连接
        headerLogicChain.appendNext(logicChainMap.get("default"));

        // 4. 返回顺序第一的节点
        return logicChainMap.get(ruledModels[0]);

    }

    @Data
    @Builder
    @AllArgsConstructor
    @NoArgsConstructor (force = true)
    public static class StrategyAwardVO{

        /** 抽奖id，内部使用 */
        private final Integer awardId;
        /** 抽奖类型 */
        private final String logicModel;
        /** 抽奖奖品规则 */
        private String awardRuleValue;

    }



    @Getter
    @AllArgsConstructor
    public enum LogicModel{

        RULE_DEFAULT("default","默认抽奖"),
        RULE_BLACKLIST("rule_blacklist","黑名单抽奖"),
        RULE_WEIGHT("rule_weight","权重抽奖"),
        ;

        private final String code;
        private final String info;
    }

}
